
import Vue from 'vue'
import Vuex from 'vuex'
import { login,logout } from '@/api/system'
import snackbar from "@/stores/snackbar"
import {setToken,getToken} from '@/plugins/util.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    barColor: 'rgba(0, 0, 0, .8), rgba(0, 0, 0, .8)',
    barImage: 'https://demos.creative-tim.com/material-dashboard/assets/img/sidebar-1.jpg',
    drawer: null,
    token: getToken()
  },
  mutations: {
    SET_BAR_IMAGE (state, payload) {
      state.barImage = payload
    },
    SET_DRAWER (state, payload) {
      state.drawer = payload
    },
    SET_TOKEN (state,token){
      state.token = token
      setToken(token)
    }
  },
  modules:{
    snackbar
  },
  actions: {

    handleLogin({commit},{username,password}){
      username = username.trim()
      return new Promise((resolve,reject) => {
        login({username,password}).then(res => {
          commit('SET_TOKEN',res.token)  
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    handleLogout({state,commit}){
      return new Promise((resolve,reject) => {
        logout().then(res => {
          commit('SET_TOKEN','')
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }

    
  },
})
